/*
 * @Author: Yhd you@example.com
 * @Date: 2023-03-14 19:47:59
 * @LastEditors: Yhd you@example.com
 * @LastEditTime: 2023-03-14 20:39:51
 * @FilePath: \electron\saveFile.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const {
    ipcMain
} = require("electron");
const request = require('request')
const fs = require('fs');
const path = require("path");

ipcMain.on('save-img', async (e, url, dir, option) => {
    saveImg(url, dir, option)
})

function saveImg(url, dir = 'coverimg', option = {}) {
    let type = url.split('.').pop().split('?')[0];
    // 判断 dir 是否存在 如果不存在则创建
    let exists = fs.existsSync(path.resolve(__dirname, dir))
    if (!exists) fs.mkdirSync(path.resolve(__dirname, dir))
    let option_str = ''
    for (let key in option) {
        option_str += `&${key}=${option[key]}`
    }

    request({
        url
    }).pipe(fs.createWriteStream(path.resolve(__dirname, `${dir}/${+new Date()}${option_str}.${type}`)))
}

module.exports = {
    saveImg
}